import axios from "axios";
import router from '@/router'
import { ls } from "../store";
import { refreshTokenTime } from "./auth";

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API
})

service.interceptors.request.use(config => {
    let token = ls.get('token')
    if(token && token != 'null'){
        config.headers.Authorization = token?.token
        refreshTokenTime(token.expiresIn)
    }
    return config
}, error => {
    return Promise.reject(error.response)
})

service.interceptors.response.use(response => {
    if(response.status === 200){
        if(response.data.code === 401){
            router.push('/login');
            ls.set('token', null)
            throw response.data.msg;
        }
        return response.data
    }
    throw Error(response.status.toString())
}, error => {
    console.log(error, 'err')
    return Promise.reject(error)
})

export default service